package com.lm.basic;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 9:23 2025/3/13
 */
public class Response extends MyHttpServletResponse{
    private int status = 200;
    private String message = "OK";
    private Map<String,String> headers = new HashMap<>();
    private LmServletOutputStream ServletOutputStream;
    private OutputStream socketOutputStream;
    private Request request;

    final private byte SP = ' ';
    final private byte CR = '\r';
    final private byte LF = '\n';


    public Response(Request request) {
        this.request = request;
        this.ServletOutputStream = new LmServletOutputStream();
        try {
            this.socketOutputStream = request.getSocket().getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setStatus(int sc, String sm) {
        status = sc;
        message = sm;
    }


    @Override
    public void addHeader(String name, String value) {
        headers.put(name,value);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return ServletOutputStream;
    }

    public void Complete() throws IOException {
        sendResponseLine();
        sendResponseHeader();
        sendResponseBody();
    }

    private void sendResponseLine() throws IOException {
        socketOutputStream.write(request.getProtocol().getBytes());
        socketOutputStream.write(SP);
        socketOutputStream.write(status);
        socketOutputStream.write(SP);
        socketOutputStream.write(message.getBytes());
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }

    private void sendResponseHeader() throws IOException {
        if (!headers.containsKey("Content-Length")) {
            headers.put("Content-Length", String.valueOf(ServletOutputStream.getPos()));
        }
        if (!headers.containsKey("Content-Type")) {
            headers.put("Content-Type", "text/plain;charset=utf-8");
        }
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            socketOutputStream.write(entry.getKey().getBytes());
            socketOutputStream.write(":".getBytes());
            socketOutputStream.write(entry.getValue().getBytes());
            socketOutputStream.write(CR);
            socketOutputStream.write(LF);
        }
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }

    private void sendResponseBody() throws IOException{
        socketOutputStream.write(ServletOutputStream.getBytes());
    }


}
